<template>
  <div class="high advanced-search advanced-search-1">
    <div class="popover"
         :class="{
      moving: moving,
      dialogVisible: dialogVisible
    }"
         v-show="opened"
    >
      <button class="config-button" @click="handleSearchConfig">
        <i class="iconfont icon-peizhi"/>
        <div class="novice-boot-box-wrap" style="position: relative" v-if="!getNoviceKeyStatus.advancedSearchCustomLayout">
          <div class="novice-circle-group " style="position: absolute;top: -35px;right: -15px;cursor: default;">
            <div class="novice-circle4"></div>
            <div class="novice-circle3"></div>
            <div class="novice-circle2"></div>
            <div class="novice-circle1"></div>
          </div>
          <div style="position: absolute;top: -112px;left:-112px ;padding-bottom: 10px;z-index: 100;cursor: default;">
            <novice-boot
              NoviceKey="advancedSearchCustomLayout"
              :NoviceArr="[{title: '', text: $t('public.searchSettingsNovice1')}]"
              @updateGuidanceSuccess="updateGuidanceSuccess"
            ></novice-boot>
          </div>
        </div>
      </button>
      <!-- <div class="form-mark" v-if="dialogVisible"></div> -->
      <el-form class="high-ranking-search" ref="ruleForm"
               :inline="true" label-position="top"
               :rules="computeRules"
               :model="formStacked.form"
      >
        <div class="search-condition">
          <div class="default-form">
            <template v-for="(item,index) in dealedFormItems">
              <el-tooltip class="robotSessionTip" effect="dark" :content="$t('webchat.robotSessionExplain')" placement="right-start">
                <i class="icon iconfont icon-tishi" v-if="item.name === 'robotSession'"></i>
              </el-tooltip>
              <el-form-item
                v-if="item._type === '_localed'"
                :key="item.name"
                :label="item.label"
                :prop="item.name"
                :class="[
                item.inputType === 'time' || item.inputType === 'radioInput' ? 'add-width' : '',
                item.inputType === 'multi' ? 'multi-label' : '',
                item.inputType === 'rangeInput' ? 'cdr-call': '',
                item.inputType === 'area' ? 'add-width-linkage': '',
                item.name ==='CALL_TIME_LENGTH_END' || item.name === 'QUEUE_TIME_LENGTH_END' || item.name === 'RING_TIME_LENGTH_END'?'whiteFont':'',
                item.name ==='ownercom'?'ownercom':'',
                item.inputType === 'no' ? 'minus-width' : '',
                item.name === currentItemName ||
                (item.name && item.name.replace('_END','_BEGIN') === currentItemName) ||
                (item.name && item.name.replace('_BEGIN','_END') === currentItemName)
                ? 'current-item' : ''
              ]"
              >
                <div class="mark" v-if="dialogVisible" @click="currentItemName=item.name">
                  <!-- <div class="sequence">{{index | sequence}}</div> -->
                </div>
                <span class="offerTimeWarn"
                      v-if="item.name === 'OFFERING_TIME' && callTimeLimit > 0"
                      v-html="$t('call.offerTimeWarn', {calltimeLimit: callTimeLimit})"
                ></span>
                <area-linkage ref="areaLinkage"
                              v-if="item.inputType==='area'"
                              :isMerge="true"
                              :isSearch="true"
                              :provinceName="item.provinceName"
                              :cityName="item.cityName"
                              :provinceValue="formStacked.form[item.provinceName]"
                              :cityValue="formStacked.form[item.cityName]"
                              :districtValue="formStacked.form[item.districtName]"
                              @valueChange="changeData"
                ></area-linkage>

                <el-input size="mini"
                          v-if="item.inputType==='input'"
                          v-model.trim="formStacked.form[item.name]"
                          :placeholder="item.placehoder?item.placehoder:''"
                          @blur="valueFiter(item.name)"
                ></el-input>

                <template v-if="item.inputType==='rangeInput'">

                  <el-input style="width:90%" size="mini"
                            v-model.trim="formStacked.form[item.name]"
                            :placeholder="$t('public.pleaseEnter')"
                  >
                    <template slot="append">{{$t('public.seconds')}}</template>
                  </el-input>

                  <span class="public-to"
                        v-if="
                    item.name !== 'CALL_TIME_LENGTH_END' &&
                    item.name !== 'RING_TIME_LENGTH_END' &&
                    item.name !== 'QUEUE_TIME_LENGTH_END'
                  "
                  >{{$t('public.to')}}</span>

                </template>

                <el-autocomplete class="inline-input" style="width:100%"
                                 v-if="item.inputType==='serverNo'"
                                 v-model.trim="formStacked.form[item.name]"
                                 :fetch-suggestions="querySearchServerNo"
                                 :trigger-on-focus="true"
                                 @select="handleSelect"
                ></el-autocomplete>

                <el-select size="mini"
                           v-if="item.inputType==='select'"
                           v-model.trim="formStacked.form[item.name]"
                           :multiple="item.multiple"
                           :allow-create="item.allowCreate"
                           :filterable="item.filterable"
                           :collapse-tags="item.collapseTags"
                           :placeholder="$t('public.pleasePick')"
                           @click.stop.native="remoteSearch(item.remoteMethod)"
                           @change="changeData(formStacked.form[item.name], item.name)"
                >
                  <el-option
                    v-for="(item2,index) in item.data"
                    :label="item2.label"
                    :value="item2.value"
                    :key="index"
                  ></el-option>
                </el-select>
                <selectTree v-if="item.inputType==='selectTree'" @change='changeData' :model='formStacked.form[item.name]'></selectTree>
                <el-cascader
                  v-if = "item.inputType === 'cascader'"
                  :options="item.data"
                  v-model.trim="formStacked[item.name]"
                  :value = 'formStacked[item.name]'
                  change-on-select
                  @change="changeData(formStacked[item.name], item.name)"
                ></el-cascader>
                <el-date-picker size="mini" type="date" align="left"
                                v-if="item.inputType==='date'"
                                v-model.trim="formStacked.form[item.name]"
                                :id="[item.name + '1', item.name + '2']"
                                :editable="false"
                                :placeholder="$t('public.pleasePick')"
                                @focus="datePickerFocus"
                                @blur = "datePickerBlur"
                ></el-date-picker>

                <el-date-picker size="mini" type="datetimerange" align="right" style="width:400px"
                                v-if="item.inputType==='time'"
                                v-model.trim="formStacked.form[item.name]"
                                :id="[item.name + '3', item.name + '4']"
                                :editable="false"
                                :picker-options="pickerOptions2"
                                :placeholder="$t('public.timeRanges')"
                                :clearable="item.name === 'OFFERING_TIME'?false:true"
                                :popper-class="item.name === 'OFFERING_TIME'?'hide-datetime-clear':''"
                                @focus="datePickerFocus"
                                @blur = "datePickerBlur"
                ></el-date-picker>

                <div v-if="item.inputType==='checkbox'">
                  <el-checkbox-group  v-model.trim="formStacked.form[item.name]">
                    <el-checkbox
                      v-if="item.inputType==='checkbox'"
                      v-for="(item2,index) in item.data"
                      :label="item2.value"
                      :key="index"
                    >
                      {{item2.label}}
                  </el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-if="item.inputType === 'radioInput'">
                  <el-radio-group v-model.trim="formStacked.form[item.radioName]">
                    <el-radio size="mini" :label="`lt__${$t('webchat.lessThan')}`">{{$t('webchat.lessThan')}}</el-radio>
                    <el-radio size="mini" :label="`gt__${$t('webchat.moreThan')}`">{{$t('webchat.moreThan')}}</el-radio>
                    <el-radio size="mini" :label="`eq__${$t('webchat.equal')}`">{{$t('webchat.equal')}}</el-radio>
                  </el-radio-group>
                  <el-input size="mini" class="radioInputwidth" v-model.trim="formStacked.form[item.inputName]"></el-input>
                </div>

                <div v-if="item.inputType==='radio'">
                  <el-radio-group  v-model.trim="formStacked.form.custom[item.name]">
                    <el-radio size="mini" v-if="item.inputType==='radio'"
                              v-for="(item2,index) in item.data"
                              :label="item2.value"
                              :key="index"
                    ></el-radio>
                  </el-radio-group>
                </div>

                <i v-if="item.inputType==='no'"></i>

                <label-select
                  v-if="item.inputType === 'multi'"
                  :filterable="item.filterable ? true : false"
                  :stringFlag="true"
                  :resetSelect = 'resetSelect'
                  :isClear="isClear"
                  @labelSelect="changeData"
                  :isNoLabel="true"
                ></label-select>

                <owner-tree-select ref="ownerTree"
                                   v-if="item.inputType === 'owner'"
                                   :businessType="type"
                                   :name="item.name"
                                   :owner="owner"
                                   @owner-change="handleOwnerChange"
                                   @owner-reset="handleOwnerReset"
                ></owner-tree-select>
              </el-form-item>

              <el-form-item
                v-if="item._type === '_custom'"
                :key="item.name"
                :label="item.label"
                :class="[
                item.inputType==='time' || item.inputType==='date' || item.inputType==='datetime' || item.inputType == 'textarea' ? 'add-width' : '',
                item.inputType==='no' ? 'minus-width' : '',
                item.inputType==='checkbox' || item.inputType ==='radio' ? 'all-width' : '',
                item.name ===currentItemName?'current-item':''
              ]"
              >
                <div class="mark" v-if="dialogVisible" @click="currentItemName=item.name">
                  <!-- <div class="sequence">{{index | sequence}}</div> -->
                </div>

                <el-input size="mini"
                          v-if="item.inputType==='input'"
                          v-model.trim="formStacked.form.custom[item.name]"
                ></el-input>

                <el-select size="mini"
                           v-if="item.inputType==='select'"
                           multiple
                           collapse-tags
                           v-model.trim="formStacked.form.custom[item.name].$in"
                           :placeholder="$t('public.pleasePick')"
                           @change="changeData(formStacked.form.custom[item.name], item.name, 'true', item.cascadeIndex)"
                >
                  <el-option
                    v-for="(item2,index) in item.data" :key="index"
                    v-if="item.inputType==='select'"
                    :label="item2.label"
                    :value="item2.value"
                  >
                  </el-option>
                </el-select>

                <v-cascsder
                  v-if="item.inputType==='cascader'"
                  :optionsId="item.data.dicId"
                  :initCascaderValue="formStacked.form.custom[item.name]"
                  :formId="item.name"
                  :isSearch="true"
                  @change="handleCascader"
                ></v-cascsder>

                <el-date-picker size="mini" type="daterange" align="right"
                                v-if="item.inputType==='date'"
                                style="width: 400px"
                                v-model.trim="formStacked.form.custom[item.name]"
                                :id="item.name + index"
                                :editable="false"
                                :picker-options="pickerOptions2"
                                :placeholder="$t('public.pleasePick')"
                                @focus="datePickerFocus"
                                @blur = "datePickerBlur"
                ></el-date-picker>
                <el-date-picker size="mini" type="datetimerange" align="right"
                                v-if="item.inputType==='datetime'"
                                style="width: 400px"
                                v-model.trim="formStacked.form.custom[item.name]"
                                :id="item.name + index"
                                :editable="false"
                                :picker-options="pickerOptions2"
                                :placeholder="$t('public.timeRanges')"
                                @focus="datePickerFocus"
                                @blur="datePickerBlur"
                ></el-date-picker>
                <el-date-picker size="mini" type="datetimerange" align="right" style="width:400px"
                                v-if="item.inputType==='time'"
                                v-model.trim="formStacked.form.custom[item.name]"
                                :id="item.name + index"
                                :editable="false"
                                :picker-options="pickerOptions2"
                                :placeholder="$t('public.timeRanges')"
                                @focus="datePickerFocus"
                                @blur="datePickerBlur"
                ></el-date-picker>

                <div v-if="item.inputType==='checkbox'">
                  <el-checkbox-group  v-model.trim="formStacked.form.custom[item.name]">
                    <el-checkbox
                      v-if="item.inputType==='checkbox'"
                      v-for="(item2,index) in item.data" :key="index"
                      :label="item2.value"
                    >
                      {{item2.label}}
                  </el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-if="item.inputType==='radio'">
                  <el-radio-group  v-model.trim="formStacked.form.custom[item.name]">
                    <el-radio size="mini"
                              v-if="item.inputType==='radio'"
                              v-for="(item2, index) in item.data" :key="index"
                              :label="item2.value"
                    >
                      {{item2.label}}
                  </el-radio>
                  </el-radio-group>
                </div>

                <el-input size="mini" type="textarea"
                          v-if="item.inputType==='textarea'"
                          v-model="formStacked.form.custom[item.name]"
                ></el-input>

                <i v-if="item.inputType==='no'"></i>
              </el-form-item>
            </template>
          </div>
        </div>
        <el-form-item class="all-width btn-group footer-btn-group" style="z-index: 0">
          <el-button class="primary_btn rest-btn" :disabled="dialogVisible" @click="resetForm">{{$t("public.reset")}}</el-button>
          <el-button type="primary"  class="primary_btn" :disabled="dialogVisible" @click="submitForm('ruleForm')">{{$t("public.search")}}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div @click.stop="toggle" class="toggle-btn">
      <el-tooltip class="item" effect="dark" :content="$t('public.advSearch')" placement="bottom">
        <i class="iconfont icon-gaojisousuo"></i>
      </el-tooltip>
    </div>
  </div>
</template>
<script>
  import {checkform} from '@/utils/validate'
  import AreaLinkage from '../../../ui-modules/area-linkage/AreaLinkage.vue'
  import OwnerTreeSelect from '../../agent-tree/OwnerTreeSelect.vue'
  import LabelSelect from '../../phone-bar/LabelSelect.vue'
  import Cascader from '../../cache/Cascader'
  import noviceBoot from '@/components/public-modules/novice-boot/index.vue'
  import { resetForm, deepClone, phoneFilterChats } from '@/utils/m7Utils.js'
  import selectTree from '../../../public-modules/select-tree/index.vue'
  export default {
    name: 'AdvancedSearch',
    /**
     * [props 该组件所需要的参数]
     * @type {
     *   type        业务类型
     *   typeType    业务tab
     * }
     */
    props: {
      type: String,
      activeName: String,
      adv: Object,
      isClear: Boolean,
      callServerNo: Array,
      isCall: Boolean,
      callTimeLimit: Number,
      formItemsConfig: {
        type: Object,
        default () {
          return null
        }
      }
    },
    data () {
      return {
        owner1Item: {},
        pickerOptions2: {
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
              const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
              picker.$emit('pick', [startTime, endTime])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
              const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
              picker.$emit('pick', [startTime, endTime])
            }
          }, {
            text: this.$t('sms.thisThreeMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
              const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
              picker.$emit('pick', [startTime, endTime])
            }
          }]
        },
        resetSelect: false,
        opened: false,
        emitData: {},
        editingFormItemsConfig: null,
        currentItemName: '',
        dialogVisible: false,
        moving: false,
        getNoviceKeyStatus: {},
        dateFocus: false
      }
    },
    watch: {
    },
    components: {
      AreaLinkage,
      OwnerTreeSelect,
      'v-cascsder': Cascader,
      LabelSelect,
      noviceBoot,
      selectTree
    },
    methods: {
      handleSearchConfig () {
        this.resetForm()
        this.$refs.AdvancedSearchConfigDialog.toggle()
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-高级搜索布局配置'])
      },
      valueFiter (key) {
        if (key !== 'phone') return
        this.formStacked.form.phone = phoneFilterChats(this.formStacked.form.phone)
      },
      submitForm (formName) {
        let self = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let form = self.formStacked.form
            if (form) {
              if (form.processMember === null || form.processMember === '') {
                self.$emit('ifRemark', false)
              } else {
                self.$emit('ifRemark', true)
              }
              if (parseInt(form.CALL_TIME_LENGTH_BEGIN) >= parseInt(form.CALL_TIME_LENGTH_END)) {
                this.$message.error(this.$t('call.callTimeError'))
                return
              } else if (parseInt(form.QUEUE_TIME_LENGTH_BEGIN) >= parseInt(form.QUEUE_TIME_LENGTH_END)) {
                this.$message.error(this.$t('call.queueTimeError'))
                return
              } else if (parseInt(form.RING_TIME_LENGTH_BEGIN) >= parseInt(form.RING_TIME_LENGTH_END)) {
                this.$message.error(this.$t('call.ringTimeError'))
                return
              }
              let offerTime = form.OFFERING_TIME
              if (offerTime && offerTime[0] && offerTime[1]) {
                let sTime = ''
                let eTime = ''
                if (typeof offerTime[0] === 'string') {
                  sTime = new Date(offerTime[0]).getTime()
                  eTime = new Date(offerTime[1]).getTime()
                } else {
                  sTime = offerTime[0].getTime()
                  eTime = offerTime[1].getTime()
                }
                let oneDay = 1000 * 3600 * 24
                let Days = parseInt((eTime - sTime) / oneDay)
                if (this.callTimeLimit > 0) { // 只有大于0的时候需要限制时间搜索范围，-1的情况不控制时间
                  if (Days > 31 * this.callTimeLimit) { // ss
                    this.$message.error(this.$t('call.callTimeLimitWarn', {calltimeLimit: this.callTimeLimit}))
                    return
                  }
                }
              }
            }
            // for( let item of self.emitData) {
            //   if (self.emitData[key] ===)
            // }
            // let newEmitData = fo    self.emitData.map(item => {
            //   if (typeof item === 'string') {
            //     return phoneFilterChats(item)
            //   }
            // })
            console.debug(self.EmitData)
            self.$emit('advSearch', false, 1, self.EmitData)
            document.getElementsByTagName('body')[0].click()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm () {
        this.resetSelect = true
        if (this.isCall) {
          this.$emit('restForm')
        } else {
          resetForm(this.formStacked.form)
        }
        if (this.$refs.areaLinkage && this.$refs.areaLinkage.length) {
          let obj = this.$refs.areaLinkage[0]
          obj.province = null
          obj.city = null
          obj.district = null
        }
        this.$refs.ruleForm.resetFields()
        if (this.formStacked.form.temp_id) {
          this.formStacked.form.temp_id = null
        }
        if (this.$refs.ownerTree && this.$refs.ownerTree.length) {
          this.$refs.ownerTree[0].$emit('resetValue')
        }
      },
      changeData (value, key, custom, cascadeIndex) {
        let emitData = {selectName: key, selectValue: value}
        if (key === 'multiCallLabel') {
          this.resetSelect = false
        }
        if (custom) {
          emitData.custom = true
          emitData.cascadeIndex = cascadeIndex
        }
        this.emitData = emitData
        this.$emit('selectChange', emitData)
      },
      handleCascader (data) {
        let emitData = { selectName: 'cascader', selectValue: data.val, name: data.id, custom: true }
        this.$emit('selectChange', emitData)
      },
      remoteSearch (methodName) {
        if (methodName) {
          this.$emit(methodName)
        }
      },
      handleOwnerChange (obj) {
        let emitData = { selectName: obj.type, selectValue: `${obj._id}__${obj.displayName || obj.label}`, name: obj.name }
        this.$emit('selectChange', emitData)
      },
      handleOwnerReset (name) {
        let emitData = { selectName: 'ownercom', selectValue: '' }
        if (name) {
          emitData.name = name
        }
        this.$emit('selectChange', emitData)
      },
      toggle () {
        this.opened = !this.opened
      },
      querySearchServerNo (queryString, callback) {
        let restaurants = this.callServerNo
        let results = queryString ? restaurants.filter(this.createFilterServerNo(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        callback(results)
      },
      createFilterServerNo (queryString) {
        return (restaurant) => {
          return (restaurant.value.indexOf(queryString.toLowerCase()) > -1)
        }
      },
      handleSelect (item) {
        if (this.formStacked.form.CALLED_NO) {
          let callEndIndex = this.formStacked.form.CALLED_NO.lastIndexOf(']')
          if (callEndIndex > 0) {
            this.formStacked.form.CALLED_NO = this.formStacked.form.CALLED_NO.substring(callEndIndex + 1, this.formStacked.form.CALLED_NO.length)
            // this.formStacked.form.CALLED_NO = this.formStacked.form.CALLED_NO.substring(0, callEndIndex)
          }
        }
        if (this.formStacked.form.CALL_NO) {
          let callIndex = this.formStacked.form.CALL_NO.lastIndexOf(']')
          if (callIndex > 0) {
            this.formStacked.form.CALL_NO = this.formStacked.form.CALL_NO.substring(callIndex + 1, this.formStacked.form.CALL_NO.length)
            // this.formStacked.form.CALL_NO = this.formStacked.form.CALL_NO.substring(0, callIndex)
          }
        }
      },
      clickFun (e) {
        if (!this.$el.contains(e.target) && !this.dateFocus) {
          this.opened = false
        }
      },
      updateGuidanceSuccess () {
        let guidance = this.$getCache('guidance')
        this.getNoviceKeyStatus = guidance || {'advancedSearchCustomLayout': true} // 服务不对，或者是没有这个对象时，默认不显示。webchatSessionLocking为气泡的key
      },
      datePickerFocus () {
        this.dateFocus = true
      },
      datePickerBlur () {
        this.dateFocus = false
      }
    },
    computed: {
      formStacked () {
        // 若高级搜索出现关于座席组件 单独提取 单独渲染
        // 解决之前循环中 v-if 座席数据较大是渲染过慢 页面假死的问题
        this.owner1Item = {}
        // this.adv.advSearchOptions.localed.filter((val) => {
        //   if (val.inputType === 'owner') {
        //     this.owner1Item = val
        //   }
        // })
        return this.adv
      },
      computeRules () {
        let validateMoblie = (rule, value, callback) => {
          if (value !== '') {
            let match = checkform(value, 'Mobile')
            if (match) {
              callback(new Error(this.$t(match)))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
        let validateEmail = (rule, value, callback) => {
          if (value !== '') {
            let match = checkform(value, 'Email')
            if (match) {
              callback(new Error(this.$t(match)))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
        let validateNum = (rule, value, callback) => {
          if (value !== '') {
            let match = checkform(value, 'Number3')
            if (match) {
              callback(new Error(this.$t(match)))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
        let rules = {}
        let localItem = this.formStacked.advSearchOptions.localed
        if (localItem) {
          localItem.forEach((item) => {
            if (item.validateType === 'Number3') {
              rules[item.name] = [{validator: validateNum, trigger: 'blur'}]
            } else if (item.validateType === 'Mobile') {
              rules[item.name] = [{validator: validateMoblie, trigger: 'blur'}]
            } else if (item.validateType === 'Email') {
              rules[item.name] = [{validator: validateEmail, trigger: 'blur'}]
            }
          })
        }
        return rules
      },
      owner () {
        let form = deepClone(this.formStacked.form)
        let ownercom = form.ownercom ? form.ownercom : ''
        let owner = form.owner ? form.owner : ''
        let ownerdep = form.ownerdep ? form.ownerdep : ''

        // 工单特有的
        let ownercomCreateUser = form.ownercomCreateUser ? form.ownercomCreateUser : ''
        let createUser = form.createUser ? form.createUser : ''
        let ownerdepCreateUser = form.ownerdepCreateUser ? form.ownerdepCreateUser : ''
        let master = form.master ? form.master : ''

        // 通话特有的
        let disposalAgent = form.DISPOSAL_AGENT ? form.DISPOSAL_AGENT : ''

        // 在线咨询
        let user = form.user ? form.user : ''

        // 邮件
        let agent = form.agent ? form.agent : ''

        return ownercom + owner + ownerdep + ownercomCreateUser + createUser + ownerdepCreateUser + master + disposalAgent + agent + user
      },
      formItems () {
        var formItems = []

        if (this.adv && this.adv.advSearchOptions) {
          var localed = this.adv.advSearchOptions.localed
          var custom = this.adv.advSearchOptions.custom

          var index = 0
          if (localed) {
            localed.forEach(item => {
              var newItem = deepClone(item)
              newItem._type = '_localed'
              newItem._index = index++
              formItems.push(newItem)
            })
          }

          if (custom) {
            custom.forEach(item => {
              var newItem = deepClone(item)
              newItem._type = '_custom'
              newItem._index = index++
              formItems.push(newItem)
            })
          }
        }

        return formItems
      },
      dealedFormItems () {
        var formItems = deepClone(this.formItems)
        var formItemsConfig = this.editingFormItemsConfig || this.formItemsConfig

        formItems = formItems.filter(item => {
          var shown = true
          var itemName = item.name

          if (item.name.endsWith('_END')) {
            itemName = item.name.replace('_END', '_BEGIN')
          }

          if (formItemsConfig && formItemsConfig[itemName]) {
            var config = formItemsConfig[itemName]
            shown = !config.hidden
          }

          return shown
        })

        formItems.sort((aItem, bItem) => {
          var aOrder
          var bOrder
          var config
          var itemName

          if (aItem.name && aItem.name.endsWith('_END')) {
            itemName = aItem.name.replace('_END', '_BEGIN')
            if (formItemsConfig && formItemsConfig[itemName]) {
              config = formItemsConfig[itemName]
              aOrder = config.order + 0.5
            }
          }

          if (bItem.name && bItem.name.endsWith('_END')) {
            itemName = bItem.name.replace('_END', '_BEGIN')
            if (formItemsConfig && formItemsConfig[itemName]) {
              config = formItemsConfig[itemName]
              bOrder = config.order + 0.5
            }
          }

          if (formItemsConfig && formItemsConfig[aItem.name]) {
            config = formItemsConfig[aItem.name]
            aOrder = config.order
          }

          if (formItemsConfig && formItemsConfig[bItem.name]) {
            config = formItemsConfig[bItem.name]
            bOrder = config.order
          }

          function isNum (n) {
            return !isNaN(n)
          }

          if (isNum(aOrder) && !isNum(bOrder)) {
            return -1
          }

          if (!isNum(aOrder) && isNum(bOrder)) {
            return 1
          }

          if (isNum(aOrder) && isNum(bOrder)) {
            return aOrder - bOrder
          }

          return aItem._index - bItem._index
        })
        return formItems
      }
    },
    filters: {
      sequence: function (value) {
        return value < 9 ? '0' + (value + 1) : (value + 1)
      }
    },
    beforeMount () {
      this.updateGuidanceSuccess()
    },
    mounted () {
      document.addEventListener('click', this.clickFun)
    },
    beforeDestroy () {
      document.removeEventListener('click', this.clickFun)
    }
  }
</script>

<style lang="stylus" scoped>
</style>
